package com.tsd.shiro.config;

import com.tsd.core.shiro.IShiroConst;
import com.tsd.shiro.realm.SysUserRealm;
import com.tsd.system.entity.SysUserExt;
import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Collection;

/**
 * @ClassName: ShiroModularRealmAuthorizer
 * @Description: TODO
 * @Author: Hillpool
 * @Date: 2022/7/18 10:48
 * @Version: 1.0
 */
public class ShiroModularRealmAuthorizer extends ModularRealmAuthorizer {

    @Override
    public boolean isPermitted(PrincipalCollection principals, String permission) {
        super.assertRealmsConfigured();
        // 所有Realm
        Collection<Realm> realms = super.getRealms();
        Object principal = principals.getPrimaryPrincipal();
        String realmName = null;
        if (principal instanceof SysUserExt) {
            realmName = IShiroConst.REALM_NAME_SYS_USER;
        }
        if (realmName != null) {
            for (Realm realm : realms) {
                if (!(realm instanceof Authorizer) || !realmName.equals(realm.getName())) {
                    continue;
                }
                if (IShiroConst.REALM_NAME_SYS_USER.equals(realm.getName())) {
                    return ((SysUserRealm) realm).isPermitted(principals, permission);
                }
            }
        }
        return false;
    }
}
